package com.example.experiment4sqlite

import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.appcompat.app.AppCompatActivity
import com.example.experiment4sqlite.utils.UserDbHelper

class InsertUserActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ? window flag
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_insert_user)
        init()
    }

    fun init() {
        val nameEdit = findViewById<EditText>(R.id.insert_name)
        val stuNumberEdit = findViewById<EditText>(R.id.insert_number)
        val spinner = findViewById<Spinner>(R.id.insert_sex)

        lateinit var selectSex: String

        spinner.onItemSelectedListener
        //为选择性别下拉列表添加选择事件
        spinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
                //获取选择的值
                selectSex = this@InsertUserActivity.resources.getStringArray(R.array.sex).get(i)
                Log.d(TAG, "get sex: $selectSex")
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }

        val ageEdit = findViewById<EditText>(R.id.insert_age)
        val saveBtn = findViewById<Button>(R.id.save_usermes)

        //获取用户输入的用户名、密码、年纪
        saveBtn.setOnClickListener {
            if (stuNumberEdit.text.toString() == "" ||
                ageEdit.text.toString() == "" ||
                nameEdit.text.toString() == "") {
                Toast.makeText(this, "请先输入信息！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val nameStr = nameEdit.text.toString()
            // this@InsertUserActivity is not need? 弹出提示用户名的toast
            Toast.makeText(this, nameStr, Toast.LENGTH_SHORT).show()

            val stuNumberStr = stuNumberEdit.text.toString()
            val age = ageEdit.text.toString().toInt()
            //调用数据库操作类的插入方法
            val userDbHelper =
                UserDbHelper(this)
            val db: SQLiteDatabase = userDbHelper.writableDatabase
            Log.d(TAG, "sex: $selectSex")
            userDbHelper.addUser(db, nameStr, stuNumberStr, selectSex, age)
            // 跳转到用户信息总表
            val intent =
                Intent(this, FindAndDelUserActivity::class.java)
            startActivity(intent)
        }

    }
}